<template>
  <div class="admin-approvals">
    <div class="page-header">
      <h2>审核管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="hasPermission('approval_batch')"
          type="primary" 
          @click="handleBatchApprove" 
          :disabled="!hasSelectedItems"
        >
          <el-icon><Check /></el-icon>
          批量通过
        </el-button>
        <el-button 
          v-if="hasPermission('approval_batch')"
          type="danger" 
          @click="handleBatchReject" 
          :disabled="!hasSelectedItems"
        >
          <el-icon><Close /></el-icon>
          批量拒绝
        </el-button>
        
      </div>
    </div>

    <!-- 申请类型筛选 -->
    <div class="filter-section">
      <el-radio-group v-model="activeType" @change="handleTypeChange">
        <el-radio-button label="all">全部申请</el-radio-button>
        <el-radio-button label="exhibitor">参展报名</el-radio-button>
        <el-radio-button label="visitor">观众预登记</el-radio-button>
        <el-radio-button label="media">媒体注册</el-radio-button>
        <el-radio-button label="visa">签证申请</el-radio-button>
        <el-radio-button label="ticket">票务预订</el-radio-button>
        <el-radio-button label="group">组团观展</el-radio-button>
        <el-radio-button label="booking">展会预定</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索申请人/公司名称"
        style="width: 200px"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select v-model="filterStatus" placeholder="审核状态" clearable @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option label="待审核" value="pending" />
        <el-option label="已通过" value="approved" />
        <el-option label="已拒绝" value="rejected" />
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="申请开始日期"
        end-placeholder="申请结束日期"
        @change="handleSearch"
      />

      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 申请列表 -->
    <el-table 
      :data="filteredData" 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="type" label="申请类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applicantName" label="申请人" width="120" />
      <el-table-column prop="company" label="公司/机构" width="200" show-overflow-tooltip />
      <el-table-column prop="contactInfo" label="联系方式" width="150" />
      <el-table-column prop="applyTime" label="申请时间" width="180" />
      <el-table-column prop="status" label="审核状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reviewer" label="审核人" width="120" />
      <el-table-column prop="reviewTime" label="审核时间" width="180" />
      <el-table-column prop="remarks" label="备注" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button 
              v-if="hasPermission('approval_view') && row.status === 'pending'"
              type="primary" 
              link 
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              v-if="hasPermission('approval_approve') && row.status === 'pending'"
              type="success" 
              link 
              @click="handleApprove(row)"
            >
              <el-icon><Check /></el-icon>
              通过
            </el-button>
            <el-button 
              v-if="hasPermission('approval_reject') && row.status === 'pending'"
              type="danger" 
              link 
              @click="handleReject(row)"
            >
              <el-icon><Close /></el-icon>
              拒绝
            </el-button>
            <el-button 
              v-if="hasPermission('approval_view') && row.status !== 'pending'"
              type="primary" 
              link 
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      :title="`查看申请详情 - ${currentApplication?.type ? getTypeText(currentApplication.type) : ''}`"
      width="70%"
    >
      <div v-if="currentApplication" class="application-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请类型">
            {{ getTypeText(currentApplication.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusType(currentApplication.status)">
              {{ getStatusText(currentApplication.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ currentApplication.applicantName }}
          </el-descriptions-item>
          <el-descriptions-item label="公司/机构">
            {{ currentApplication.company }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentApplication.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱地址">
            {{ currentApplication.email }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ currentApplication.applyTime }}
          </el-descriptions-item>
          <el-descriptions-item label="审核人">
            {{ currentApplication.reviewer || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ currentApplication.reviewTime || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentApplication.remarks || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 根据申请类型显示详细信息 -->
        <div class="detail-section">
          <h4>详细信息</h4>
          <div v-if="currentApplication.type === 'visa'" class="visa-detail">
            <p><strong>签证类型：</strong>{{ currentApplication.visaType }}</p>
            <p><strong>国籍：</strong>{{ currentApplication.nationality }}</p>
            <p><strong>护照号码：</strong>{{ currentApplication.passportNumber }}</p>
            <p><strong>来华目的：</strong>{{ currentApplication.purpose }}</p>
            <p><strong>预计入境：</strong>{{ currentApplication.entryDate }}</p>
            <p><strong>预计离境：</strong>{{ currentApplication.exitDate }}</p>
          </div>
          
          <div v-else-if="currentApplication.type === 'ticket'" class="ticket-detail">
            <p><strong>票务类型：</strong>{{ currentApplication.ticketType }}</p>
            <p><strong>预订数量：</strong>{{ currentApplication.quantity }}</p>
            <p><strong>参观日期：</strong>{{ currentApplication.visitDate }}</p>
            <p><strong>参观目的：</strong>{{ currentApplication.purpose }}</p>
          </div>
          
          <div v-else-if="currentApplication.type === 'group'" class="group-detail">
            <p><strong>团体名称：</strong>{{ currentApplication.groupName }}</p>
            <p><strong>预计人数：</strong>{{ currentApplication.groupSize }}</p>
            <p><strong>计划采购：</strong>{{ currentApplication.products }}</p>
            <p><strong>联系人：</strong>{{ currentApplication.contactName }}</p>
            <p><strong>联系人职务：</strong>{{ currentApplication.contactPosition }}</p>
          </div>
          
          <div v-else-if="currentApplication.type === 'media'" class="media-detail">
            <p><strong>媒体类型：</strong>{{ currentApplication.mediaType }}</p>
            <p><strong>头衔：</strong>{{ currentApplication.title }}</p>
            <p><strong>单位：</strong>{{ currentApplication.organization }}</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="`审核申请 - ${currentApplication?.applicantName}`"
      width="500px"
    >
      <el-form :model="reviewForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="reviewForm.result">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核意见">
          <el-input
            v-model="reviewForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview" :loading="reviewing">
          提交审核
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { approvalApi } from '@/api/admin'
import {
  Check,
  Close,
  Download,
  Search,
  View
} from '@element-plus/icons-vue'

export default {
  name: 'AdminApprovals',
  components: {
    Check,
    Close,
    Download,
    Search,
    View
  },
  setup() {
    // 状态
    const loading = ref(false)
    const reviewing = ref(false)
    const activeType = ref('all')
    const searchKeyword = ref('')
    const filterStatus = ref('')
    const dateRange = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const selectedItems = ref([])
    const viewDialogVisible = ref(false)
    const reviewDialogVisible = ref(false)
    const currentApplication = ref(null)
    const approvalData = ref([])
    
    // 权限检查 - 开发阶段暂时开放所有权限
    const hasPermission = (permission) => {
      // 开发阶段：暂时返回 true，确保所有按钮都能显示
      console.log(`权限检查: ${permission} - 开发阶段暂时开放`)
      return true
    }

    // 审核表单
    const reviewForm = reactive({
      result: 'approved',
      remarks: ''
    })

    // 数据加载方法
    const loadApprovalData = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          type: activeType.value === 'all' ? '' : activeType.value,
          keyword: searchKeyword.value,
          status: filterStatus.value
        }
        
        if (dateRange.value && dateRange.value.length === 2) {
          params.startDate = dateRange.value[0]
          params.endDate = dateRange.value[1]
        }

        const response = await approvalApi.getApprovalPage(params)
        if (response.code === '200') {
          approvalData.value = response.data.records || []
          total.value = response.data.total || 0
        }
      } catch (error) {
        console.error('加载审批数据失败:', error)
        ElMessage.error('加载审批数据失败')
      } finally {
        loading.value = false
      }
    }
    
    const getItemType = (item) => {
      if (item.companyName) return 'exhibitor'
      if (item.visitorType) return 'visitor'
      if (item.mediaOrg) return 'media'
      if (item.passportNumber) return 'visa'
      if (item.ticketType) return 'ticket'
      return 'other'
    }

    // 过滤后的数据
    const filteredData = computed(() => {
      return approvalData.value.filter(item => {
        if (activeType.value !== 'all' && item.type !== activeType.value) return false
        if (searchKeyword.value && !item.applicantName.includes(searchKeyword.value) && !item.company.includes(searchKeyword.value)) return false
        if (filterStatus.value && item.status !== filterStatus.value) return false
        if (dateRange.value && dateRange.value.length === 2) {
          const applyDate = new Date(item.applyTime)
          const start = dateRange.value[0]
          const end = dateRange.value[1]
          if (applyDate < start || applyDate > end) return false
        }
        return true
      })
    })

    // 是否有选中的项目
    const hasSelectedItems = computed(() => {
      return selectedItems.value.length > 0
    })

    // 获取申请类型标签类型
    const getTypeTagType = (type) => {
      const types = {
        exhibitor: 'success',
        visitor: 'warning',
        media: 'primary',
        visa: 'danger',
        ticket: 'warning',
        group: 'success',
        booking: 'info'
      }
      return types[type] || 'info'
    }

    // 获取申请类型文本
    const getTypeText = (type) => {
      const texts = {
        exhibitor: '参展报名',
        visitor: '观众预登记',
        media: '媒体注册',
        visa: '签证申请',
        ticket: '票务预订',
        group: '组团观展',
        booking: '展会预定'
      }
      return texts[type] || '未知'
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger'
      }
      return types[status] || 'info'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝'
      }
      return texts[status] || '未知'
    }

    // 处理类型切换
    const handleTypeChange = () => {
      currentPage.value = 1
      loadApprovalData()
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadApprovalData()
    }

    // 重置搜索
    const resetSearch = () => {
      searchKeyword.value = ''
      filterStatus.value = ''
      dateRange.value = []
      handleSearch()
    }

    // 处理分页
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      loadApprovalData()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadApprovalData()
    }

    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedItems.value = selection
    }

    // 查看详情
    const handleView = (row) => {
      currentApplication.value = row
      viewDialogVisible.value = true
    }

    // 审核申请
    const handleApprove = (row) => {
      currentApplication.value = row
      reviewForm.result = 'approved'
      reviewForm.remarks = ''
      reviewDialogVisible.value = true
    }

    // 拒绝申请
    const handleReject = (row) => {
      currentApplication.value = row
      reviewForm.result = 'rejected'
      reviewForm.remarks = ''
      reviewDialogVisible.value = true
    }

    // 提交审核
    const submitReview = async () => {
      if (!reviewForm.remarks.trim()) {
        ElMessage.warning('请输入审核意见')
        return
      }

      reviewing.value = true
      
      try {
        const currentUser = JSON.parse(localStorage.getItem('userInfo'))?.userName || '管理员'
        const id = currentApplication.value.id
        const status = reviewForm.result
        const comment = reviewForm.remarks
        const auditUser = currentUser
        
        // 根据申请类型调用不同的审核API
        switch (currentApplication.value.type) {
          case 'exhibitor':
            await approvalApi.approveExhibitor(id, status, comment, auditUser)
            break
          case 'visitor':
            await approvalApi.approveVisitor(id, status, comment, auditUser)
            break
          case 'media':
            await approvalApi.approveMedia(id, status, comment, auditUser)
            break
          case 'visa':
            await approvalApi.approveVisa(id, status, comment, auditUser)
            break
          case 'ticket':
            await approvalApi.approveTicket(id, status, comment, auditUser)
            break
          default:
            throw new Error('未知的申请类型')
        }
        
        ElMessage.success('审核提交成功')
        reviewDialogVisible.value = false
        currentApplication.value = null
        
        // 重新加载数据
        await loadApprovalData()
      } catch (error) {
        console.error('审核提交失败:', error)
        ElMessage.error('审核提交失败: ' + (error.message || '未知错误'))
      } finally {
        reviewing.value = false
      }
    }

    // 批量通过
    const handleBatchApprove = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要批量通过选中的 ${selectedItems.value.length} 个申请吗？`,
          '确认批量操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 调用批量审核API
        const currentUser = JSON.parse(localStorage.getItem('userInfo'))?.userName || '管理员'
        await approvalApi.batchApprove(
          selectedItems.value.map(item => item.id),
          'approved',
          '批量审核通过',
          currentUser
        )
        
        ElMessage.success('批量审核成功')
        selectedItems.value = []
        await loadApprovalData() // 重新加载数据
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量审核失败:', error)
          ElMessage.error('批量审核失败: ' + (error.message || '未知错误'))
        }
      }
    }

    // 批量拒绝
    const handleBatchReject = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要批量拒绝选中的 ${selectedItems.value.length} 个申请吗？`,
          '确认批量操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 调用批量审核API
        const currentUser = JSON.parse(localStorage.getItem('userInfo'))?.userName || '管理员'
        await approvalApi.batchApprove(
          selectedItems.value.map(item => item.id),
          'rejected',
          '批量审核拒绝',
          currentUser
        )
        
        ElMessage.success('批量审核成功')
        selectedItems.value = []
        await loadApprovalData() // 重新加载数据
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量审核失败:', error)
          ElMessage.error('批量审核失败: ' + (error.message || '未知错误'))
        }
      }
    }

    // 导出数据
    const handleExport = () => {
      ElMessage.info('导出功能开发中')
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadApprovalData()
    })

    return {
      loading,
      reviewing,
      activeType,
      searchKeyword,
      filterStatus,
      dateRange,
      currentPage,
      pageSize,
      total,
      selectedItems,
      hasSelectedItems,
      viewDialogVisible,
      reviewDialogVisible,
      currentApplication,
      reviewForm,
      filteredData,
      hasPermission,
      getTypeTagType,
      getTypeText,
      getStatusType,
      getStatusText,
      handleTypeChange,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleView,
      handleApprove,
      handleReject,
      submitReview,
      handleBatchApprove,
      handleBatchReject,
      handleExport
    }
  }
}
</script>

<style scoped>
.admin-approvals {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.application-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.detail-section p {
  margin: 5px 0;
  color: #666;
}

.detail-section strong {
  color: #333;
}
</style>
